package Tracker.server.model;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.json.JSONObject;

public class User extends JSONObject {
	public final int id;
	String name;
	String passHash;
	
	public User(int id, String n, String p) throws Exception {
		this.id = id;
		this.map.put("id", id);
		
		if(n == null || p == null) throw new Exception("Invalid name or password");
		try {
			this.name = n;
			this.map.put("name", name);
			
			this.passHash = hash(p);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void setName(String n) {
		this.name = n;
		this.map.put("name", n);
	}
	
	public void setPassword(String p) throws NoSuchAlgorithmException {
		this.passHash = hash(p);
	}
	
	public boolean authenticate(String n, String p) throws NoSuchAlgorithmException {
		return this.name.equals(n) && this.passHash.equals(hash(p));
	}
	
	static String hash(String pass) throws NoSuchAlgorithmException {
		MessageDigest m = MessageDigest.getInstance("MD5");
		m.update(pass.getBytes());
		
		return new String(m.digest());
	}
}
